package com.brucekong.slm.service.layim;

import com.brucekong.slm.common.ListUtil;
import com.brucekong.slm.mapper.layim.ImMapper;
import com.brucekong.slm.model.layim.ImDomain;
import com.brucekong.slm.model.user.UserDomain;
import com.brucekong.slm.service.user.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.brucekong.slm.config.WebSecurityConfig.SESSION_KEY;

@Service
public class ImService {

    @Resource
    private ImMapper imMapper;
    @Resource
    private UserService userService;

    public Map getImList(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<ImDomain> imDomainList = imMapper.getImList();
        // 拿到结果先按照groupName分组
        Map<String, List<ImDomain>> resMap = ListUtil.groupBy(imDomainList, row -> {
            String groupName  = row.getGroupName();
            if (groupName != null){
                return groupName;
            }
            return null;
        });
        HttpSession session = request.getSession();
        UserDomain user = (UserDomain)session.getAttribute(SESSION_KEY);
        if (null != user){
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getRealName());
            userMap.put("status", user.getStatus());
            userMap.put("sign", user.getSign());
            userMap.put("avatar", user.getAvatar());
            List<Map<String, Object>> groupMapList = new ArrayList<>();
            Map<String, Object> groupMap;
            List<Map<String, Object>> groupItemMapList;
            Map<String, Object> groupItemMap;

            // 遍历分组的resMap
            for (List<ImDomain> list : resMap.values()){
                // 清空
                groupMap = new HashMap<>();
                groupItemMapList = new ArrayList<>();

                for (ImDomain im : list){
                    groupItemMap = new HashMap<>();

                    groupMap.put("groupname", im.getGroupName());
                    groupMap.put("id", im.getGroupId());

                    groupItemMap.put("username", im.getRealName());
                    groupItemMap.put("id", im.getUserId());
                    groupItemMap.put("avatar", im.getAvatar());
                    groupItemMap.put("sign", im.getSign());
                    groupItemMap.put("status", im.getStatus());

                    groupItemMapList.add(groupItemMap);
                }
                groupMap.put("list", groupItemMapList);
                groupMapList.add(groupMap);
            }
            map.put("mine", userMap);
            map.put("friend", groupMapList);
        }
        return map;
    }
}